import React, {useEffect, useState, forwardRef, useImperativeHandle, useRef} from 'react';
import {Form, Input, Upload, message, Select} from "antd";
import ImgCrop from "antd-img-crop";
import style from "./BlogText.module.scss"
import {addBlogImg, getBlogTypeListApi} from "../AddBlogApi";
import {useSearchParams} from "react-router-dom";

const BlogText = (props, ref) => {
    const [blogTypeList, setBlogTypeList] = useState([])
    const [blogTextData, setBlogTextData] = useState({})
    const formRef = useRef()
    const [searchParams] = useSearchParams()
    const [imgUrl, setImgUrl] = useState('')

    const rules = [
        [{required: true, message: '博客类型不能为空!'}],
        [{required: true, message: '博客封面介绍不能为空!'}],
    ]

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('图片类型不对!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片大小不能大于 2MB!');
        }
        const formData = new FormData()
        formData.append('file', file)
        addBlogImg(formData).then(res => {
            console.log(process.env.REACT_APP_URL + res.data.url)
            setImgUrl(process.env.REACT_APP_URL + res.data.url)
        })
        return false;
    };

    // 页面数据初始化
    useEffect(() => {
        getBlogTypeListApi().then(res => {
            if (res.code === '200') {
                setBlogTypeList(res.data.rows.map(i => {
                    return {
                        value: i.blogTypeName,
                        label: i.blogTypeName,
                        id: i.id
                    }
                }))
            }
        }).catch((e) => {
            console.log(e)
        })
    }, [])

    useEffect(() => {
        // 如果路由带id参数
        if (searchParams.has("id")) {
            // 设置图片
            const data = {
                blogTitle: props.editBlog.blogTitle,
                blogCoverTitle: props.editBlog.blogCoverTitle,
                blogTypeId: props.editBlog.blogTypeId,
                blogTypeNameK: props.editBlog.blogTypeNameK,
                title: props.editBlog.blogTitle,
            }
            setBlogTextData(data)
            setImgUrl(props.editBlog.blogCoverImage)
            formRef.current.setFieldsValue(data)
        }
    }, [props.editBlog])


    // 输入框修改
    const inputChange = (e, name) => {
        setBlogTextData({...blogTextData, [name]: e.target.value})
    }

    // 选择框修改
    const handleChange = (value) => {
        const typeData = blogTypeList.filter(i => {
            return i.value === value
        })
        setBlogTextData({...blogTextData, blogTypeName: typeData[0].value, blogTypeId: typeData[0].id})
    };

    // 触发校验
    const verifyFormData = async () => {
        try {
            await formRef.current.validateFields()
            return true
        } catch (e) {
            return false
        }
    }

    // 抛出数据
    useImperativeHandle(ref, () => {
        return {
            imgUrl,
            blogTextData,
            verifyFormData,
        }
    })

    return (
        <div>
            <div className={style.BlogTextBody}>
                <div className={style.BlogTextImg}>
                    <div className={style.BlogTextFile}>
                        <ImgCrop rotationSlider width={200}>
                            <Upload
                                listType="picture-card"
                                maxCount={1}
                                name="file"
                                action="#"
                                showUploadList={false}
                                beforeUpload={beforeUpload}
                            >
                                {imgUrl ? (
                                    <img src={imgUrl} alt="avatar" style={{height: '100%'}}/>) : '+ Upload'}
                            </Upload>
                        </ImgCrop>
                    </div>
                </div>
                <div className={style.BlogTextForm}>
                    <Form
                        name="basic"
                        ref={formRef}
                        labelCol={{span: 6,}}
                        wrapperCol={{span: 20,}}
                        style={{maxWidth: 600,}}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="博客标题"
                            colon={true}
                            name="title"
                            rules={rules[0]}>
                            <Input placeholder="博客标题" onChange={(e) => inputChange(e, 'title')}
                            />
                        </Form.Item>
                        <Form.Item
                            label="博客类型"
                            colon={true}
                            name="blogTypeNameK"
                            rules={rules[0]}>
                            <Select
                                onChange={handleChange}
                                options={blogTypeList}
                            >
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="封面介绍"
                            name="blogCoverTitle"
                            rules={rules[1]}>
                            <Input.TextArea
                                onChange={(e) => inputChange(e, 'blogCoverTitle')}
                                autoSize={false}
                                maxLength={200}
                                style={{
                                    height: 120,
                                }}
                                placeholder={'请输入长度为200的封面内容'}
                            />
                        </Form.Item>
                    </Form>
                </div>
            </div>

        </div>

    );
}

export default forwardRef(BlogText);
